const xml2js = require('xml2js');
const ejs = require('ejs');
const moment = require('moment');
const sha1 = require('sha1');
exports.wechatXml2Json = (xml) => {
    return new Promise((resolve,reject)=>{
        xml2js.parseString(xml,{trim:true},(err,content)=>{
            if(err){
                reject(err);
                return;
            }
            const data = formatJson(content);
            resolve(data);
        });
    });
}

exports.wechatJson2Xml = (json) => {
    const tpl = `<xml>
                    <ToUserName><![CDATA[<%=ToUserName%>]]></ToUserName> 
                    <FromUserName><![CDATA[<%=FromUserName%>]]></FromUserName> 
                    <CreateTime><%=CreateTime%></CreateTime>
                    <MsgType><![CDATA[<%=MsgType%>]]></MsgType>
                    <% if(MsgType === 'text'){%>
                    <Content><![CDATA[<%-Content%>]]></Content>
                    <% }else if(msgType === 'image'){ %>
                    <Image><MediaId><![CDATA[<%=Content.mediaId%>]]></MediaId></Image>
                    <% }else if(msgType === 'voice'){ %>
                    <Voice><MediaId><![CDATA[<%=Content.mediaId%>]]></MediaId></Voice>
                    <% }else if(msgType === 'video'){ %>
                    <Video><MediaId><![CDATA[<%=Content.mediaId%>]]></MediaId><Title><![CDATA[<%=Content.title%>]]></Title><Description><![CDATA[<%=Content.description%>]]></Description></Video>
                    <% }else if(msgType === 'music'){ %>
                    <Music><Title><![CDATA[<%=Content.title%>]]></Title><Description><![CDATA[<%=Content.description%>]]></Description><MusicUrl><![CDATA[<%=Content.musicUrl%>]]></MusicUrl><HQMusicUrl><![CDATA[<%=Content.hqMusicUrl%>]]></HQMusicUrl><ThumbMediaId><![CDATA[<%=Content.thumbMediaId%>]]></ThumbMediaId></Music>
                    <% }else if(msgType === 'news'){ %>
                    <ArticleCount><%=Content.length%></ArticleCount>
                    <Articles>
                    <% content.forEach(function(item){ %>  
                    <item><Title><![CDATA[<%=item.title%>]]></Title><Description><![CDATA[<%=item.description%>]]></Description><PicUrl><![CDATA[<%=item.picUrl%>]]></PicUrl><Url><![CDATA[<%=item.url%>]]></Url></item>      
                    <%})%>
                    </Articles>
                    <%}%>
                </xml>`;
    const template = ejs.compile(tpl);
    return template(json);
    
}
// jssdk 签名认证
exports.getJssdkSignature = (url,jsapi_ticket) => {
    const noncestr = Math.random().toString(36).substr(2,15);
    const timestamp = moment().unix();
    const args = {
        url,
        jsapi_ticket,
        timestamp,
        noncestr
    }
    let keys = Object.keys(args);
    keys = keys.sort();
    let str = '';
    keys.forEach((key)=>{
        str+='&'+ key + '=' + args[key]
    });
    str = str.substring(1);
    return {
        signature:sha1(str),
        timestamp,
        noncestr
    }
}


function formatJson (json) {
    for(let key in json){
        if(typeof json[key] === 'object' && json[key] instanceof Array ){
            if(json[key].length === 1){
                json[key] = json[key][0];
            }
        }else if(typeof json[key] === 'object'){
            json[key] = formatJson(json[key]);
        }
    }
    return json;
}

